package service;

import java.io.IOException;
import java.io.InputStream;

/**
 * @author yk
 * @version 1.0
 * @date 2021/2/26
 * 把请求信息封装为Request对象（根据InputSteam输入流封装）
 */
public class Request {

    /**请求方式，比如GET/POST */
    private String method;
    /**例如 /index.html */
    private String url;
    private String host;
    private Integer port;

    /** Socket的到的输入流  */
    private InputStream inputStream;

    public Request() {
    }

    public String getHost() {
        return host;
    }

    public void setHost(String host) {
        this.host = host;
    }

    public Integer getPort() {
        return port;
    }

    public void setPort(Integer port) {
        this.port = port;
    }

    public Request(InputStream inputStream) throws IOException {
        this.inputStream = inputStream;

        // 由于网络间断性，怕inputStream.available()得到的长度为null，则while循环知道查到长度
        int count = 0;
        while ( count == 0 ){
            count = inputStream.available();
        }
        byte[] bytes = new byte[count];
        // 把流的数据读取到bytes数组中
        inputStream.read(bytes);

        String inputStr = new String(bytes);
        // GET /index.html HTTP/1.1
        String firstLineStr = inputStr.split("\\n")[0];
        String[] split = firstLineStr.split(" ");
        this.method = split[0];
        // 把/index.html变成index.html
        this.url = split[1];
        System.out.println("=====>>method:" + method);
        System.out.println("=====>>url:" + url);
    }

    public String getMethod() {
        return method;
    }

    public void setMethod(String method) {
        this.method = method;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public InputStream getInputStream() {
        return inputStream;
    }

    public void setInputStream(InputStream inputStream) {
        this.inputStream = inputStream;
    }

}
